<template>
	<view class="order-manage">
		<!-- 顶部编辑区域 -->
		<view class="top-bar">
			<view class="cardform" labelPosition="left">
				<view class="form-item">
					<view class="form-label">负责人:</view>
					<u-input 
						v-model="verification.director" 
						class="form-input" 
						placeholder="请输入负责人姓名"
					></u-input>
				</view>
				<view class="form-item">
					<view class="form-label">身份证号码:</view>
					<u-input 
						v-model="verification.idCard" 
						class="form-input" 
						placeholder="请输入身份证号码"
						maxlength="18"
					></u-input>
				</view>
				<view class="form-item">
					<view class="form-label">手机号:</view>
					<u-input 
						v-model="verification.mobile" 
						class="form-input" 
						placeholder="请输入手机号"
						type="number"
						maxlength="11"
					></u-input>
				</view>
				<view class="form-item">
					<view class="form-label">店名:</view>
					<u-input 
						v-model="merchantsinfo.name" 
						class="form-input" 
						placeholder="请输入店名"
					></u-input>
				</view>
				<view class="form-item">
					<view class="form-label">工商营业持照号码:</view>
					<u-input 
						v-model="verification.businessLicenseId" 
						class="form-input" 
						placeholder="请输入营业执照号码"
					></u-input>
				</view>
				<view class="form-item">
					<view class="form-label">经营区域:</view>
					<u-input 
						v-model="merchantsinfo.operatingArea" 
						class="form-input" 
						placeholder="请输入经营区域"
					></u-input>
				</view>
				<view class="form-item">
					<view class="form-label">地址:</view>
					<u-input 
						v-model="merchantsinfo.address" 
						class="form-input" 
						placeholder="请输入详细地址"
					></u-input>
				</view>
			</view>
			
			<view class="cardform" labelPosition="left">
				<view class="section-title">商家简介</view>
				<u-input 
					v-model="merchantsinfo.description" 
					class="form-textarea" 
					placeholder="请输入商家简介"
					type="textarea"
					rows="4"
				></u-input>
			</view>
			
			<view class="cardform" labelPosition="left">
				<view class="section-title">身份证正反面照片</view>
				<view class="image-group">
					<view class="upload-area" @click="chooseImage('front')">
						<image 
							:src="verification.front"
							mode="widthFix"
							class="info-image"
						></image>
						<view class="delete-icon" @click.stop="deleteImage('front')">×</view>
						<view class="upload-text">点击上传正面</view>
					</view>
					<view class="upload-area" @click="chooseImage('opposite')">
						<image 
							:src="verification.opposite"
							mode="widthFix"
							class="info-image"
						></image>
						<view class="delete-icon" @click.stop="deleteImage('opposite')">×</view>
						<view class="upload-text">点击上传反面</view>
					</view>
				</view>
			</view>
			
			<view class="cardform" labelPosition="left">
				<view class="section-title">营业持照</view>
				<view class="image-group">
					<view class="upload-area" @click="chooseImage('businessLicenseImg')">
						<image 
							:src="verification.businessLicenseImg"
							mode="widthFix"
							class="info-image"
						></image>
						<view class="delete-icon" @click.stop="deleteImage('businessLicenseImg')">×</view>
						<view class="upload-text">点击上传营业执照</view>
					</view>
				</view>
			</view>
			
			<view class="cardform" labelPosition="left">
				<view class="section-title">门店照片</view>
				<view class="image-group">
					<view class="upload-area" @click="chooseImage('merchantimg.img')">
						<image 
							:src="merchantimg.img"
							mode="widthFix"
							class="info-image"
						></image>
						<view class="delete-icon" @click.stop="deleteImage('merchantimg.img')">×</view>
						<view class="upload-text">点击上传门店照片</view>
					</view>
				</view>
			</view>
		</view>
		
		<view class="button-container">
			<u-button 
				text="保存修改" 
				class="modify-button"
				@click="saveChanges"
			></u-button>
		</view>
	</view>
</template>

<script>
	import {
		get,
		post,
		put
	} from '../../utils/request.js'
	export default {
		data() {
			return {
				// 商家信息表单数据
				merchantsinfo: {
					name: '',
					operatingArea: '',
					address: '',
					description: ''
				},
				// 验证信息表单数据
				verification: {
					director: '',
					idCard: '',
					mobile: '',
					businessLicenseId: '',
					businessLicenseIdImg:'',
					front:'',
					opposite:'',
					sysuserId:''
				},
				merchantimg:{
					img:'',
					sysuserId:''
				},
				fileList1: [],
			}
		},
		methods: {
			chooseImage(type) {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: async (res) => {
						const tempFile = res.tempFiles[0];
						const localPath = tempFile.path;
						// 根据类型保存到正确的对象中（关键修复）
						if (type === 'merchantimg.img') {
							this.merchantimg.img = localPath; // 门店照片存到 shopphoto
						} else {
							this.verification[type] = localPath; // 其他照片存到 verification
						}
			
						// 尝试上传到服务器
						try {
							const uploadRes = await this.uploadFile(tempFile.path);
							if (uploadRes && uploadRes.startsWith('http')) {
								// 延迟更新为网络路径
								setTimeout(() => {
									if (type === 'merchantimg.img') {
										this.merchantimg.img = uploadRes;
									} else {
										this.verification[type] = uploadRes;
									}
								}, 300);
							} else {
								throw new Error('网络路径无效，保留本地路径');
							}
						} catch (err) {
							uni.showToast({
								title: '图片上传失败',
								icon: 'none'
							});
						}
					}
				});
			},
			async uploadFile(filePath) {
				return new Promise((resolve, reject) => {
					const token = uni.getStorageSync('token') || '';
					uni.uploadFile({
						url: 'http://localhost/dev-api/file/upload',
						filePath: filePath,
						name: 'file',
						header: {
							'Authorization': 'Bearer ' + token,
						},
						formData: {},
						success: (res) => {
							if (res.statusCode === 200) {
								try {
									const response = JSON.parse(res.data);
									if (response.code === 200) {
										// 1. 适配后端返回的不同格式（根据实际返回调整）
										let imagePath = '';
										if (typeof response.data === 'string') {
											// 情况1：后端直接返回路径字符串（如 "/statics/xxx.jpg"）
											imagePath = response.data;
										} else if (response.data && response.data.url) {
											// 情况2：后端返回对象，路径在url字段（如 { url: "/statics/xxx.jpg" }）
											imagePath = response.data.url;
										} else {
											// 无法解析路径时直接报错
											reject(new Error('无法从后端响应中获取图片路径'));
											return;
										}
			
										// 2. 拼接完整URL（确保以http开头且格式正确）
										const baseUrl = 'http://127.0.0.1:9300';
										let fileUrl = '';
										if (imagePath.startsWith('http')) {
											// 若后端已返回完整URL，直接使用
											fileUrl = imagePath;
										} else {
											// 拼接baseUrl（注意处理斜杠，避免重复或缺失）
											fileUrl = baseUrl + (imagePath.startsWith('/') ? '' :
												'/') + imagePath;
										}
										resolve(fileUrl);
									} else {
										reject(new Error(`上传失败：${response.msg || '未知错误'}`));
									}
								} catch (e) {
									reject(new Error(`解析响应失败：${e.message}`));
								}
							} else {
								reject(new Error(`上传失败，状态码：${res.statusCode}`));
							}
						},
						fail: (err) => {
							reject(new Error(`请求失败：${err.errMsg}`));
						}
					});
				});
			},
			// uView上传组件处理
			async afterRead(event) {
				const lists = [].concat(event.file);
				const name = event.name;
			
				lists.forEach((item, index) => {
					this[`fileList${name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					});
			
					this.uploadFile(item.url).then(res => {
						if (res) {
							this[`fileList${name}`][index].status = 'success';
							this[`fileList${name}`][index].url = res;
							this.formData.businessLicense = res; // 保存营业执照URL
						} else {
							this[`fileList${name}`][index].status = 'failed';
							this[`fileList${name}`][index].message = '上传失败';
						}
					});
				});
			},
			
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1);
			},
			// 删除图片
			deleteImage(type) {
				// 清除对应的数据（关键修复）
				if (type === 'merchantimg.img') {
					this.merchantimg.img = '';
				} else {
					this.verification[type] = '';
				}
			},
			// 保存修改
			async saveChanges() {
				console.log(this.merchantsinfo)
				console.log(this.merchantimg)
				console.log(this.verification)
				// // 简单验证
				// if (!this.verification.director) {
				// 	return uni.showToast({ title: '请填写负责人', icon: 'none' });
				// }
				// if (!this.verification.mobile) {
				// 	return uni.showToast({ title: '请填写手机号', icon: 'none' });
				// }
				// if (!this.merchantsinfo.name) {
				// 	return uni.showToast({ title: '请填写店名', icon: 'none' });
				// }
				// console.log(this.merchantsinfo);
				// console.log(this.verification);
				// // 保存到本地存储
				const res=await put('/dev-api/system/merchant',this.merchantsinfo)
				const res1=await put('/dev-api/system/verification',this.verification)
				const res2=await put('/dev-api/system/imgs',this.merchantimg)
				// console.log(res)
				uni.setStorageSync('merchant', this.merchantsinfo);
				uni.setStorageSync('verification', this.verification);
				uni.setStorageSync('merchantimg', this.merchantimg);
				uni.navigateTo({
					url:'/pages/homepage/homepage'
				})
				// // 保存图片路径（实际项目中可能需要上传服务器）
				// const images = {
				// 	idCardFront: this.idCardFront,
				// 	idCardBack: this.idCardBack,
				// 	businessLicense: this.businessLicense,
				// 	storePhoto: this.storePhoto
				// };
				// uni.setStorageSync('merchantImages', images);
				// uni.showToast({ title: '保存成功' });
				// // 可添加返回上一页逻辑
				// // setTimeout(() => uni.navigateBack(), 1500);
			}
		},
		onLoad() {
			// 从本地存储加载已有数据（如有）
			const merchantData = uni.getStorageSync('merchant');
			const verificationData = uni.getStorageSync('verification');
			const imagesData = uni.getStorageSync('merchantimg');
			// 填充表单数据
			if (merchantData) this.merchantsinfo = merchantData;
			if (verificationData) this.verification = verificationData;
			if (imagesData) {
				this.merchantimg=imagesData
			}
		}
	}
</script>

<style>
	.order-manage {
		background-color: #f5f5f5;
		min-height: 100vh;
		padding-bottom: 100rpx; /* 为底部按钮留出空间 */
	}

	/* 顶部区域 */
	.top-bar {
		padding: 20rpx;
		background-color: #2979ff;
	}

	.delete-icon {
		position: absolute;
		top: 5rpx;
		right: 5rpx;
		width: 40rpx;
		height: 40rpx;
		background-color: rgba(0, 0, 0, 0.5);
		color: white;
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 28rpx;
	}
	/* 卡片样式 */
	.cardform {
		width: 90%;
		padding: 30rpx 5%;
		border-radius: 15rpx;
		background-color: white;
		margin-bottom: 20rpx;
	}

	/* 表单项目样式 */
	.form-item {
		display: flex;
		align-items: center;
		margin-bottom: 30rpx;
		padding-bottom: 30rpx;
		border-bottom: 1px solid #f5f5f5;
	}
	
	.form-item:last-child {
		border-bottom: none;
	}

	.form-label {
		font-weight: bold;
		width: 240rpx; /* 固定标签宽度 */
		color: #333;
		padding-right: 20rpx;
	}

	/* 输入框样式 */
	.form-input {
		flex: 1;
		height: 80rpx;
		background-color: #f9f9f9;
		border-radius: 8rpx;
		padding: 0 20rpx;
	}

	/* 文本域样式 */
	.form-textarea {
		width: 100%;
		background-color: #f9f9f9;
		border-radius: 8rpx;
		padding: 20rpx;
	}

	/*  section标题 */
	.section-title {
		font-weight: bold;
		margin-bottom: 20rpx;
		color: #333;
	}

	/* 图片上传区域 */
	.image-group {
		display: flex;
		flex-wrap: wrap;
		gap: 30rpx;
		padding: 10rpx 0;
	}

	.upload-area {
		display: flex;
		flex-direction: column;
		align-items: center;
		position: relative;
	}

	/* 图片样式 */
	.info-image {
		width: 200rpx;
		height: 200rpx;
		object-fit: cover;
		border-radius: 8rpx;
		border: 1px dashed #ddd;
	}

	.upload-text {
		margin-top: 10rpx;
		font-size: 26rpx;
		color: #666;
	}

	/* 按钮容器 */
	.button-container {
		display: flex;
		justify-content: center;
		padding: 30rpx 20rpx;
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #f5f5f5;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	/* 保存按钮样式 */
	.modify-button {
		color: white;
		background-color: blueviolet;
		border-radius: 20rpx;
		width: 400rpx;
		height: 80rpx;
		line-height: 80rpx;
	}
</style>